import pandas as pd
import numpy as np
import itertools
import pickle
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules


def load_apriori(file_path):
    try:
        with open(file_path, 'rb') as f:
            biga_load = pickle.load(f)
        return biga_load
    except FileNotFoundError:
        print(f"文件 {file_path} 不存在，将重新计算 Apriori 结果")
        return None


def save_apriori(biga_result, file_path):
    with open(file_path, 'wb') as f:
        pickle.dump(biga_result, f)


def getAsso(biga_load, tel, min_support):
    if biga_load is None:
        return {}
    tel = tel.lower()
    rules = biga_load['rules']
    selected_rules = rules[(rules['antecedents'].apply(lambda x: tel in x)) & (rules['support'] >= min_support)]
    related_skills = set()
    for index, row in selected_rules.iterrows():
        consequents = row['consequents']
        for skill in consequents:
            related_skills.add(skill)
    return related_skills


def calculate_apriori():
    df = pd.read_csv("dataset.csv")
    # 将 skill_list 列的内容拆分为列表
    transactions = df['skill_list'].apply(lambda x: x.split(",")).tolist()
    te = TransactionEncoder()
    te_ary = te.fit(transactions).transform(transactions)
    df_trans = pd.DataFrame(te_ary, columns=te.columns_)
    frequent_itemsets = apriori(df_trans, min_support=0.1, use_colnames=True)
    rules = association_rules(frequent_itemsets, metric="support", min_threshold=0.1)
    biga_result = {
        'frequent_itemsets': frequent_itemsets,
        'rules': rules
    }
    return biga_result


def print_function_call(func):
    def wrapper(*args, **kwargs):
        print(f"调用函数：{func.__name__}")
        result = func(*args, **kwargs)
        print(f"函数 {func.__name__} 返回结果：{result}")
        return result
    return wrapper


@print_function_call
def recommend_related_skills(tel):
    biga_load = load_apriori("apriori.bin")
    if biga_load is None:
        return "暂无相关技能推荐"
    related_skills = getAsso(biga_load, tel, 0.1)
    if not related_skills:
        return "暂无相关技能推荐"
    return list(related_skills)


@print_function_call
def required_skills_for_position(positionName):
    df = pd.read_csv("dataset.csv")
    position_data = df[df['positionName'] == positionName]
    if position_data.empty:
        return f"未找到职位 {positionName} 的相关信息"
    skills_list = position_data['skill_list'].apply(lambda x: x.split(",")).tolist()
    skills = [skill for sublist in skills_list for skill in sublist]
    return skills[:10]


@print_function_call
def suitable_positions_for_skill(tech_list):
    df = pd.read_csv("dataset.csv")
    tech_set = set(tech_list)
    position_scores = {}
    for index, row in df.iterrows():
        position_skills = set(row['skill_list'].split(","))
        common_skills = tech_set.intersection(position_skills)
        match_score = len(common_skills)
        position_scores[row['positionName']] = match_score
    sorted_positions = sorted(position_scores.items(), key=lambda x: x[1], reverse=True)
    top_3_positions = [pos for pos, score in sorted_positions[:3]]
    if not top_3_positions:
        return "暂无适合的岗位推荐"
    return top_3_positions

if __name__ == "__main__":
    biga_result = calculate_apriori()
    save_apriori(biga_result, "apriori.bin")
    print("Apriori 计算完成并已保存")
tools = [
    {
        "type": "function",
        "function": {
            "name": "recommend_related_skills",
            "description": "根据擅长的技术推荐关联技术",
            "parameters": {
                "type": "object",
                "properties": {
                    "tel": {"type": "string", "description": "擅长的技术，如：Python"}
                },
                "required": ["tel"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "required_skills_for_position",
            "description": "查询从事指定岗位需要学习的技术",
            "parameters": {
                "type": "object",
                "properties": {
                    "positionName": {"type": "string", "description": "职位名称，如：算法工程师"}
                },
                "required": ["positionName"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "suitable_positions_for_skill",
            "description": "根据掌握的技术推荐适合的岗位",
            "parameters": {
                "type": "object",
                "properties": {
                    "tech_list": {"type": "list", "description": "掌握的技术列表，如：['Python', '机器学习']"}
                },
                "required": ["tech_list"]
            }
        }
    }
]